﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Threading.Tasks;


namespace AsyncFileLogger
{
    class AsyncFileLogger
    {
        readonly StreamWriter StreamWriter;
        Task lastTask = null;
        readonly object lockWrite = new object();

        public AsyncFileLogger(string filepath)
        {
            FileInfo fileInfo = new FileInfo(filepath);
            StreamWriter = fileInfo.AppendText();
            StreamWriter.AutoFlush = false;
        }

        public void WriteAsync(string msg)
        {
            lock (lockWrite)
            {
                if (lastTask == null)
                    lastTask = StreamWriter.WriteLineAsync(msg);
                else
                    lastTask = lastTask.ContinueWith((_, state) =>
                    {
                        StreamWriter.WriteLine((string)state);
                    }, msg);
            }
        }

        public void Close()
        {
            lastTask.Wait();
            StreamWriter.Close();
        }
    }
}
